package com.leetcode.Offer;

public class JZ55_II {
    int maxSize;
    int minSize = 10000;
    int only = 0;//叶子节点的数目

    public boolean isBalanced(TreeNode root) {

        if (root == null) {
            return true;
        }
        dfs(root, 1);

        //还必须对每个节点都进行相同的判定,由于用到了公共变量，出错，此路行不通
        if (only > 1) {
            return (maxSize - minSize > 1 ? false : true) && isBalanced(root.left) && isBalanced(root.right);
        } else if (minSize < 3) {
            return true && isBalanced(root.left) && isBalanced(root.right);
        } else {
            return false && isBalanced(root.left) && isBalanced(root.right);
        }


    }

    //判定叶子节点数目
    private void dfs(TreeNode root, int deep) {

        //寻找最小深度必须到达节点
        if (root.left == null && root.right == null) {
            only++;
            maxSize = Math.max(maxSize, deep);
            minSize = Math.min(minSize, deep);
        }

        if (root.left != null) {
            dfs(root.left, deep + 1);
        }
        if (root.right != null) {
            dfs(root.right, deep + 1);
        }

    }
}
